package Concurrency.AsynTaskExecute;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 与Timer不同，单个定时任务的异常不会再导致整个定时任务被取消
 * 即使后台只有一个线程执行任务
 *
 * 运行程序发现，TaskB中抛出异常后，TaskA没有受到影响，继续正常执行
 */

public class ScheduledException {
    static class TaskA implements Runnable {
        @Override
        public void run() {
            System.out.println("task A");
        }
    }

    static class TaskB implements Runnable {
        @Override
        public void run() {
            System.out.println("task B");
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) {
        ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
        timer.scheduleWithFixedDelay(new TaskA(), 0, 1, TimeUnit.SECONDS);
        timer.scheduleWithFixedDelay(new TaskB(), 2, 1, TimeUnit.SECONDS);
    }
}
